package com.pi.nbcenter.device.service.pi.internal;

import java.util.Date;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import com.pi.iot.repository.huawei.bean.notify.HuaWeiIotRecord;
import com.pi.iot.repository.huawei.constants.NotifyType;
import com.pi.nbcenter.device.entity.auto.IotDeviceInfo;
import com.pi.nbcenter.device.entity.auto.IotDeviceNotificationLog;
import com.pi.nbcenter.device.mapper.auto.IotDeviceNotificationLogMapper;

@Validated
@Service
public class IotDeviceNotificationLogService {
  private static final Logger logger = 
      LoggerFactory.getLogger(IotDeviceNotificationLogService.class); 
  @Autowired
  private PiIotDevService iotDevService;
  @Autowired
  private IotDeviceNotificationLogMapper deviceNotificationLogMapper;
  
  public void addIotDeviceNotificationLog(@Valid HuaWeiIotRecord record){
    IotDeviceInfo iotDevInfo = 
        iotDevService.queryDbDeviceInfoByIotDevIdIfExist(record.getDeviceId());
    IotDeviceNotificationLog log = new IotDeviceNotificationLog();
    log.setIotDeviceId(record.getDeviceId());
    log.setNotifyContent(record.toString());
    log.setNotifyName(record.getNotifyType());
    log.setNotifyType(NotifyType.getNotifyType(record.getNotifyType()).getCode());
    log.setCreateDate(new Date());
    log.setUpdateDate(log.getCreateDate());
    log.setVersion(200L);
    if(null == iotDevInfo){
      logger.error("设备在平台不存在, 请注意: {}", log.getNotifyContent());
      log.setDeviceId(0L);
      log.setIotPlatformId(0);
    }else{
      log.setDeviceId(iotDevInfo.getId());
      log.setIotPlatformId(iotDevInfo.getIotPlatformId());
    }
    deviceNotificationLogMapper.insert(log);
  }
}
